package com.bd.scm.module.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.bd.scm.config.MyLog;
import com.bd.scm.domain.dto.login.LoginDto;
import com.bd.scm.module.login.service.LoginService;
import com.bd.utils.StringUtils;
import com.bd.utils.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Map;

/**登录Controller
 * @ClassName LoginController
 * @Description TODO
 * @Author YH
 * @Date 2019/12/30 0030 9:03
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/login")
public class LoginController extends AbstractBaseController{

  /**
   * 登录Service
   */
  @Autowired
  private LoginService loginService;

  /**
   * 登录验证
   * @param loginDto activeId 1 域登录  2工号登录  username 账号 password 密码 3 username 账号(工号) APP 4 PC
   * @return
   */
  @MyLog(value = "登陆-用户登陆")
  @PostMapping("valiLogin")
  public Result valiLogin(@RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) throws UnknownHostException {
    String clientIp = InetAddress.getLocalHost().getHostAddress();
    Result result = null;
    try {
      String verification = (String) request.getSession().getAttribute("verification");
      //清空Session
      this.removeSessionAttributr(request);
      //判断是否验证码为空
      if (StringUtils.isEmpty(verification)) {
        result = Result.error(1005, "验证码失效");
        return result;
      }
      //判断验证是否正确
      if (!verification.equals(loginDto.getVerificationCod())) {
        result = Result.error(1001, "验证码错误");
        return result;
      }
      JSONObject object = this.loginService.valiLogin(loginDto, clientIp,request);
      //判断是否登录成功
      if("00000".equals(object.getString("code"))){
        //设置普通人员
        object.put("identity",1);
        //判断该登录工号是否存在WT_GLY表
        if(Integer.valueOf(String.valueOf(request.getSession().getAttribute("wtGlyCount")))>0){
          //设置管理员
          object.put("identity",2);
          JSONObject jsonObject = (JSONObject) request.getSession().getAttribute("user");
          String userNO = object.getString("userNO");
          loginDto.setUsername(userNO);
          setLoginInfo(request, response, loginDto,jsonObject.getString("userSerial"));
        }
        result = Result.ok(object);
      }else{
        result = Result.error(object.getString("message"));
      }
    } catch (Exception e) {
      e.printStackTrace();
      result = Result.error("程序内部错误");
    }
    return result;
  }

  /**
   * 登陆逻辑
   * @param loginDto
   * @param request
   * @param response
   * @return
   * @throws UnknownHostException
   */
  @PostMapping("userLogin")
  public Result userLogin(@RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) throws UnknownHostException {
    Result result = null;
    try {
      String verification = (String) request.getSession().getAttribute("verification");
      //清空Session
      this.removeSessionAttributr(request);
      //判断是否验证码为空
      if (StringUtils.isEmpty(verification)) {
        result = Result.error(1005, "验证码失效");
        return result;
      }
      //判断验证是否正确
      if (!verification.equals(loginDto.getVerificationCod())) {
        result = Result.error(1001, "验证码错误");
        return result;
      }
      JSONObject user = this.loginService.getUser(loginDto);
      if(user != null){
        //保存Session
        //登录人信息保存到Session
        request.getSession().setAttribute("user",user);
        //保存场所信息
        request.getSession().setAttribute("findPlaceid",user.getString("placeList"));
        //保存部门信息
        request.getSession().setAttribute("findDeptid",user.getString("depList"));
        //保存菜单信息
        request.getSession().setAttribute("findMenuList",user.getString("menuList"));
        result = Result.ok(user);
      }else{
        result = Result.error("登陆失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
      result = Result.error("程序内部错误");
    }
    return result;
  }

  //清空Session
  public void removeSessionAttributr(HttpServletRequest request){
    //得到session中所有的属性名
    Enumeration em = request.getSession().getAttributeNames();
    while (em.hasMoreElements()) {
      //遍历删除session中的值
     request.getSession().removeAttribute(em.nextElement().toString());
    }
    //设置session有效期
    request.getSession().setMaxInactiveInterval(30*60*60);
  }


  // 延峰人脸登陆
  /**
   * 延峰人脸登陆
   * @param request
   * @param response
   * @return
   * @throws UnknownHostException
   */
  @PostMapping("yfLogin")
  public Result yfLogin(@RequestBody LoginDto loginDto,HttpServletRequest request, HttpServletResponse response) throws UnknownHostException {
    Result result = null;
    try {
      //清空Session
      this.removeSessionAttributr(request);
      JSONObject user = this.loginService.getUser(loginDto.getEmpNo());
      if(user != null){
        //保存Session
        //登录人信息保存到Session
        request.getSession().setAttribute("user",user);
        result = Result.ok(user);
      }else{
        result = Result.error("登陆失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
      result = Result.error("程序内部错误");
    }
    return result;
  }

}
